package ch.mylonas.saometer.data;

import processing.core.PApplet;
import ch.mylonas.saometer.config.SaoMeterConfig;

/**
 * @author Roman Mylonas
 * 
 * 	creates artificial data from the punch-device
 */
public class SerialDataMock extends SerialDataCommon implements Runnable, SerialData{

	SaoMeterConfig saoMeterConfig;

	// the random values
	final static int PUNCH_CYCLE_1 = 50;
	final static int PUNCH_CYCLE_2 = 30;
	final static int EMPTY_CYCLE = 1000;

	Thread thread;

	public SerialDataMock() {
		super();
	}

	public void init(){

		this.nrOfDataPoints = saoMeterConfig.getNrDataPoints();
		this.data = new int[NUMBER_OF_CHANNELS][this.nrOfDataPoints];
		this.resetData();

		// start the mock
		this.isRunning = true;
		thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {

		while(isRunning){

			for(int i=0; i<=EMPTY_CYCLE; i++){
				if(!isRunning){
					i--;
				}else{

					int val = (int) (saoMeterConfig.getZeroAxis());
					int[] newData = new int[2];
					newData[0] = (int)PApplet.parseInt(val);
					newData[1] = (int)PApplet.parseInt(val);
					this.shiftArray(newData);
				}

				try {
					Thread.sleep(2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			for(int i=0; i<=PUNCH_CYCLE_1; i++){
				if(!isRunning){
					i--;
				}else{

					int[] newData = new int[2];
					newData[0] = (int)(this.saoMeterConfig.getZeroAxis() - i - 95);
					newData[1] = (int)(this.saoMeterConfig.getZeroAxis());

					this.shiftArray(newData);
				}

				try {
					Thread.sleep(2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}

			for(int i=0; i<=PUNCH_CYCLE_2; i++){
				if(!isRunning){
					i--;
				}else{

					int[] newData = new int[2];
					newData[0] = (int)(Math.random()*saoMeterConfig.getMaxDataValue());
					newData[1] = (int)(Math.random()*saoMeterConfig.getMaxDataValue());

					this.shiftArray(newData);
				}

				try {
					Thread.sleep(2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}

		}

	}

	@Override
	public int[] getData(int channel) {
		return this.data[channel];
	}

	@Override
	public int getLastValue(int channel) {
		return this.data[channel][this.nrOfDataPoints-1];
	}

	public void setSaoMeterConfig(SaoMeterConfig saoMeterConfig) {
		this.saoMeterConfig = saoMeterConfig;
	}


}
